package com.kehao.leetcode.jzoffer;

import java.util.Stack;

public class JZSolution055 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private static class BSTIterator {

        Stack<TreeNode> stack = new Stack<>();

        public BSTIterator(TreeNode root) {
            if(root!=null){
                stack.push(root);
                TreeNode node = root;
                while (node.left!=null){
                    node = node.left;
                    stack.push(node);
                }
            }
        }

        public int next() {
            TreeNode node = stack.pop();
            int val = node.val;
            if(node.right!=null){
                stack.push(node.right);
                node = node.right;
                while (node.left!=null){
                    node = node.left;
                    stack.push(node);
                }
            }
            return val;
        }

        public boolean hasNext() {
            return !stack.isEmpty();
        }
    }




    private TreeNode buildTree(Integer[] treeArray){
        TreeNode[] treeNodeList = new TreeNode[treeArray.length];
        for (int i = 0; i < treeArray.length; i++) {
            if(treeArray[i]!=null){
                treeNodeList[i] = new TreeNode(treeArray[i]);
            }
        }
        for (int i = 0; i < treeNodeList.length/2; i++) {
            if(i*2+1<treeNodeList.length){
                treeNodeList[i].left = treeNodeList[i*2+1];
            }
            if(i*2+2<treeNodeList.length){
                treeNodeList[i].right = treeNodeList[i*2+2];
            }
        }
        return treeNodeList[0];
    }
}
